<template>
  <el-container>
    <el-aside width="350px">
      <el-tabs type="border-card">
        <el-tab-pane label="输入图层">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="srcRun">运行</el-button>
          </div>
          <el-form :model="srcParameter" :rules="srcRules" ref="srcParameter">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="srcParameter.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="叠加图层">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="initGeojson">运行</el-button>
          </div>
          <el-form :model="diejiaParams" :rules="diejiaParams" ref="diejiaParams">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="diejiaParams.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>                        
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="叠加分析">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="densityRun">运行</el-button>
          </div>
          <el-form :model="compositionParameter" :rules="rules" ref="compositionParameter">
            <el-form-item prop="srcTable" label="输入数据">
              <el-input  v-model="compositionParameter.srcTable" autocomplete="off" placeholder="输入数据"></el-input>
            </el-form-item>
            <el-form-item prop="newTable" label="叠加数据">
              <el-input  v-model="compositionParameter.newTable" autocomplete="off" placeholder="叠加数据" ></el-input>
            </el-form-item>
            <el-form-item prop="computeType" label="计算类型">
              <el-input  v-model="compositionParameter.computeType" autocomplete="off" placeholder="计算类型" ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'PostgisAbstractAnalysis',
    data(){
      return{        
        oldGeosjon:'{"type":"FeatureCollection","features":[{"type":"feature","geometry":{"type":"LineString","coordinates":[[116.79097232411755,32.660504759706384],[116.79037566268642,32.65963851133749]]}}]}',
        geojsonPath: '',
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
        srcParameter:{
          srcTable:"jzd",//原始数据
        },
        diejiaParams:{
          srcTable:"jzx",//原始数据          
        },
        compositionParameter:{
          srcTable:"jzd",//原始数据
          newTable: "jzx",// 叠加数据
          computeType:0.0001,// 计算类型
        },
        srcRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],                
        },
        diejiaParamsRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ]                       
        },
        rules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],
          newTable: [
            { required: true, message: '请输入叠加数据', trigger: 'blur' },
          ],
          computeType: [
            { required: true, message: '请输入计算类型', trigger: 'blur' },
          ],          
        },
      
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
          // 英文标注转换为中文   
          // mapboxgl.setRTLTextPlugin(
          //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
          // );
          this.map =  new mapboxgl.Map({
              accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
              container: 'map',
              style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
              center: [116.790402852,32.65959655],  //[116.79507,32.65542], // starting position [lng, lat]
              zoom: 15, // starting zoom
              hash: false,
              //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
              bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
              antialias: true, //抗锯齿，通过false关闭提升性能
          })
          // 设置语言
          // var language = new MapboxLanguage({ defaultLanguage: "zh" });
          // this.map.addControl(language);

          //地图导航
          var nav = new mapboxgl.NavigationControl();
          this.map.addControl(nav, 'top-right');

          // 比例尺
          var scale = new mapboxgl.ScaleControl({
              maxWidth: 100,
              unit: "metric"
          });
          this.map.addControl(scale,"bottom-left");

          // 全图
          this.map.addControl(new mapboxgl.FullscreenControl());
          // 定位
          this.map.addControl(
              new mapboxgl.GeolocateControl({
              positionOptions: {
                  enableHighAccuracy: true
              },
              trackUserLocation: true
              })
          );
          let that = this;
          this.map.on('load',function () {
              that.map.addSource('national-park',that.geojson);
            
            that.map.addLayer({
              "id": "park-boundary_line",
              "type": "line",
              "source": "national-park",              
              "layout": {
                "visibility": "visible",			
              },
              "paint": {
                "line-opacity": 1,
                "line-color": "#007799",
                "line-width": 5,				
              }            
            });
            that.map.addLayer({
              id: "park-boundary_point",
              type: "circle",
              source: "national-park",
              paint: {
                  "circle-radius": 2,
                  "circle-color": "#fff",
              }
            });
			  
			  that.map.addSource("gps-pointss",that.geojson);
			  
			  //叠加分析
			  that.map.addSource("abstract",that.geojson);
			  
			  
			  //geojson line 叠加分析数据渲染
			   that.map.addLayer({
           "id": "abstract",
           "type": "fill",
           "source": "abstract",              
           "layout": {
					 "visibility": "visible",			
				  },
          "paint": {
            "fill-color":"#00FFCC",
            'fill-opacity': 0.1,
            "fill-outline-color": "#000000",
           }
         });

              //that.map.addLayer({
               // 'id': 'polygon',
               // 'type': 'fill',
               // 'source': "gps-points",
               // 'layout': {},
               // 'paint': {
               //     'fill-color': 'red',
               //     'fill-opacity': 0.8
               // }
              //})		  
			
           

              //geojson  point 数据渲染
              that.map.addLayer({
                  id: "gps-points",
                  type: "circle",
                  source: "gps-pointss",
                  paint: {
                      "circle-radius": 2,
                      "circle-color": "#fff",
                  }
              });
              //geojson line 数据渲染
              that.map.addLayer({
                      "id": "geojson-line",
                      "type": "line",
                      "source": "gps-pointss",              
                      "layout": {
                "visibility": "visible",			
              },
                      "paint": {
                "line-opacity": 1,
                "line-color": "#45D23E",
                "line-width": 1,				
                 },
                 "maxzoom": 20,
                 "minzoom": 0,
              });
			  
			  //geojson polygon 数据渲染
			  that.map.addLayer({
                 "id": "geojson-polygon ",
                 "type": "fill",
                 "source": "gps-pointss",              
                 "layout": {
					"visibility": "visible",			
				},
                 "paint": {
					"fill-color":"#ffff",
					'fill-opacity': 1,
                 }
              });			  
             

            // that.loadGeojson()
			
		    //that.initGeojson()
			
			//叠加分析
			// that.abstractAnalysis();
              
          })
          
      },    
      /**
       * 叠加分析
       */
      densityRun(){
         debugger
        let that = this
        that.$refs["compositionParameter"].validate((valid) => {       
          if (valid) {
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.compositionParameter.srcTable)
            fd.append("newTable",that.compositionParameter.newTable)
            fd.append("computeType",that.compositionParameter.computeType)
            let url = "/analysis/abstract"
             that.$axios.post(url, fd)
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom.value)    
                features=geom.features			
                //features.push({
                // "type": "Feature",
                //  "geometry":geom,
                //  "properties": {"status": "status"}
                //})
              })
              that.map.getSource('abstract').setData({
                "type": "FeatureCollection",
                "features":[]
              })
              that.map.getSource('abstract').setData({
                "type": "FeatureCollection",
                "features":features
              })
            })
            .catch(function (error) {
              // handle error
              console.log(error);
            })   
          } else {
            console.log('error submit!!');
            return false;
          }
        });       

      },
      /**
        * 渲染geojson数据
        * 
        */
      srcRun(){
        let that = this
        that.$refs["srcParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.srcParameter.srcTable)                     
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('gps-pointss').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('gps-pointss').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },
      /**
       * 渲染geojson数据
       * 
       */
      initGeojson(){
        let that = this
        let ISNULL =false;
        if(that.geojsonPath!=""){
          ISNULL = true
        }
        console.log(that)
        if(ISNULL){
          that.map.getSource('national-park').setData({
            "type": "FeatureCollection",
            "features":[]
          })
          that.map.getSource('national-park').setData(that.geojsonPath)
          let urls = that.geojsonPath.split("https://geo.datav.aliyun.com")
          that.$axios({
            url: urls[1],
            method: 'get',
            data:{},
          })
          .then(function (res) {          
            that.jsonData = res.data
            that.map.flyTo({
              center:res.data.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
            console.log(res);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })   
        }else{          
          if(that.oldGeosjon == "" || that.oldGeosjon ==  {}){
            that.jsonData = {}
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
          }
          if(typeof(that.oldGeosjon) == "string"){
            that.jsonData = JSON.parse(that.oldGeosjon)
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
            that.map.flyTo({
              center:[that.jsonData.features[0].properties.center],
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          if(Object.prototype.toString.call(that.oldGeosjon) === '[object Object]'){
            that.jsonData = that.oldGeosjon
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
             that.map.flyTo({
              center:that.jsonData.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          
        }       
      },
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>